// const { text } = require("body-parser");

function previewFile() {
    console.log(10)
    var oImg = document.getElementById('oImg');
    var file = document.getElementById('ipt').files[0];
    var reader = new FileReader();
    
    reader.addEventListener('load', function() {
        oImg.src = this.result;
        img = oImg.src;
    }, false);
    if (file) {
        reader.readAsDataURL(file);
    }
}
function goodspreviewFile(i) {
    var oImg = document.getElementsByClassName('goodsbackImg')[i];
    var file = document.getElementsByClassName('putImg')[i].files[0];
    var reader = new FileReader();
    reader.addEventListener('load', function() {
        oImg.src = this.result;
    }, false);
    if (file) {
        reader.readAsDataURL(file);
    }
}

function previewFiles() {
    console.log(100)
    var preview = document.querySelector('#preview');
    var files   = document.getElementById("browse").files;
    function readAndPreview(file) {
    // 确保file.name符合我们要求的扩展名
    console.log(100)
        if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {  //正则表达式判断是否为图片
            console.log(1)
            var reader = new FileReader();              //创建一个FileReader()模型
            reader.addEventListener("load", function () {
                console.log(2)
                var image = new Image();                    //创建一个img对象，相当于给浏览器缓存了一张图片
                image.height = 100;           //定义图片高度为100px
                image.title = file.name;      //图片的标题为文件的名字
                image.src = this.result;      //图片的src是点击的结果
                appendInList(this.result)
                preview.appendChild(image);   //把img加到preview里面
            }, false);
            reader.readAsDataURL(file);   //读取一个file对象，同时result属性包含了图片的URL格式字符串
        }
    }
    if (files) {
    [].forEach.call(files, readAndPreview);//[]是一个用不到的空数组，用于访问与数组有关的方法
                                           //forEach是对数组的每一个元素执行一次函数
                                           //就是说如果files不为null的话，每个元素执行一遍readAndPreview
    }
}
var theFiles = new Array();
function appendInList(src){
    theFiles.push(src)
    theFiles.map(Number)     //以一个新数组的形式返回
    console.log(theFiles)
}
clearList = () =>{
    var pre = document.querySelector('#preview');
    var pres = pre.childNodes;
    for(var i = pres.length-1;i>=0;i--){
        pre.removeChild(pres[i]);
    }
    theFiles = []
    console.log(theFiles)
}
function addSpec(Obj){
    var nums = Obj.parentNode.children[0].children;
    console.log(nums)
    if(nums.length >= 1 && nums.length<20){
        var thistext = document.createElement("div")
        thistext.className = "specsin"
        thistext.onchange = function(){
            addSize()
        }
        thistext.innerHTML+=`
            <div class="size">
                <label class="lab">商品颜色:</label>
                <input type="text" placeholder="请输入商品颜色" maxlength="10">
                <label class="lab1">商品尺寸:</label>
                <input type="text" placeholder="请输入商品尺寸" maxlength="10">
                <button onclick="deleteSpec(this)">删除</button>
            </div>
        `
        document.getElementById("specs").appendChild(thistext)
    }else{
        document.getElementById("floatContent").innerHTML = "<div>"+"商品规格不能超过20个！！！"+"</div>"+"<button onclick='closethis();passwordlog()' class='newbtn'>"+"确定"+"</button>";
        document.getElementById("floatContent").classList.remove("hide");
    }
}
function addThisSpec(Obj){
    var nums = Obj.parentNode.children[0].children;
    console.log(nums)
    if(nums.length >= 1 && nums.length<20){
        var thistext = document.createElement("div")
        thistext.className = "specsin"
        thistext.innerHTML+=`
            <div class="sizeFir">
                <label class="lab">规格名称:</label>
                <input type="text" class="specname" placeholder="请输入规格名称">
                <label class="lab1">规格内容:</label>
                <input type="text" class="speccontent" placeholder="请输入规格内容">
                <button onclick="deleteThisSpec(this)">删除</button>
            </div>
        `
        document.getElementById("spec").appendChild(thistext)
    }else{
        document.getElementById("floatContent").innerHTML = "<div>"+"商品规格不能超过20个！！！"+"</div>"+"<button onclick='closethis();passwordlog()' class='newbtn'>"+"确定"+"</button>";
        document.getElementById("floatContent").classList.remove("hide");
    }
}
function deleteSpec(Obj){
    var nums = Obj.parentNode.parentNode.parentNode.children;
    console.log(nums)
    if(nums.length > 1){
        Obj.parentNode.parentNode.parentNode.removeChild(Obj.parentNode.parentNode);
    }else{
        document.getElementById("floatContent").innerHTML = "<div>"+"商品颜色与尺寸不能为空！！！"+"</div>"+"<button onclick='closethis();passwordlog()' class='newbtn'>"+"确定"+"</button>";
        document.getElementById("floatContent").classList.remove("hide");
    }
}
function deleteThisSpec(Obj){
    var nums = Obj.parentNode.parentNode.parentNode.children;
    console.log(nums)
    if(nums.length > 1){
        Obj.parentNode.parentNode.parentNode.removeChild(Obj.parentNode.parentNode);
    }else{
        document.getElementById("floatContent").innerHTML = "<div>"+"商品规格不能为空！！！"+"</div>"+"<button onclick='closethis();passwordlog()' class='newbtn'>"+"确定"+"</button>";
        document.getElementById("floatContent").classList.remove("hide");
    }
}
function closethis(){
    document.getElementById("floatContent").classList.add("hide");
}
function change(){
    document.getElementById("floatContent").innerHTML = "<div>"+"商品规格不能为空！！！"+"</div>"+"<button onclick='closethis();passwordlog()' class='newbtn'>"+"确定"+"</button>";
    document.getElementById("floatContent").classList.remove("hide");
}
function clearCover(){
    document.getElementById("oImg").src = ``
}
function addSize(){
    var sizes = document.getElementsByClassName("size");
    var thelong = sizes.length;
    var name = document.getElementById("name").value
    document.getElementById("thead").innerHTML=`
    <tr>
        <th class="th1">名称</th>
        <th class="th2">款式</th>
        <th class="th3">预览图</th>
        <th class="th4">价格与库存</th>
        <th class="th5">操作</th>
    </tr>
    `
    document.getElementById("tbody").innerHTML=``
    for(let i=0;i<thelong;i++){
        document.getElementById("tbody").innerHTML +=`
        <tr>
            <td>
                <div class="sty">
                    <div class="insty">${name}</div>
                </div>
            </td>
            <td>
                <div class="goodcolor">${sizes[i].children[1].value}</div>
                <div class="goodsize">${sizes[i].children[3].value}</div>
            </td>
            <td>
                <input type="file" class="putImg" onchange="goodspreviewFile(${i})"/><br/>
                <div class="backImg" height="200">
                    <img src="../../static/home/img/add.png" class="goodsbackImg">
                </div>
            </td>
            <td>
                <div class="price"><input type="text" class="goodprice" placeholder="请输入价格"></div>
                <div class="stock"><input type="text" class="goodstock" placeholder="请输入库存"></div>
            </td>
            <td>
                <div class="takeOff">删除</div>
            </td>
        </tr>
        `
    }
}
function uploadGood(){
    var goodsName = document.getElementById("name").value
    var goodprice = document.getElementsByClassName("goodprice")
    var goodsPrice = new Array();
    var formData = new FormData()
    for(let i = 0;i<goodprice.length ; i++){
        // goodpri = goodprice[i].value
        // goodsPrice.push(goodpri)
        // goodsPrice.map(Number)     //以数字的形式返回新数组
        formData.append('goodsPrice',goodprice[i].value);
        console.log(goodprice[i].value);
    }
    console.log("goodprice",goodsPrice)
    var goodstock = document.getElementsByClassName("goodstock")
    var goodsStock = new Array();
    for(let i = 0;i<goodstock.length ; i++){
        // goodsto = goodstock[i].value
        // goodsStock.push(goodsto)
        // goodsStock.map(Number)     //以数字的形式返回新数组
        formData.append('stock',goodstock[i].value);
    }
    var specname = document.getElementsByClassName("specname")
    var specName = new Array();
    for(let i = 0;i<specname.length ; i++){
        // goodssen = specname[i].value
        // specName.push(goodssen)
        // specName.map(Number)     //以数字的形式返回新数组
        formData.append('specName',specname[i].value);
    }
    var speccontent = document.getElementsByClassName("speccontent")
    var specContent = new Array();
    for(let i = 0;i<speccontent.length ; i++){
        // goodscon = speccontent[i].value
        // specContent.push(goodscon)
        // specContent.map(Number)     //以数字的形式返回新数组
        formData.append('specContent',speccontent[i].value);
    }
    console.log("spec",speccontent.length)
    var goodcolor = document.getElementsByClassName("goodcolor")
    var goodColor = new Array();
    for(let i = 0;i<goodcolor.length ; i++){
        // goodscol = goodcolor[i].innerHTML
        // goodColor.push(goodscol)
        // goodColor.map(Number)     //以数字的形式返回新数组
        formData.append('color',goodcolor[i].innerHTML);
    }
    var goodsize = document.getElementsByClassName("goodsize")
    var goodSize = new Array();
    for(let i = 0;i<goodsize.length ; i++){
        // goodssiz = goodsize[i].innerHTML
        // goodSize.push(goodssiz)
        // goodSize.map(Number)     //以数字的形式返回新数组
        formData.append('size',goodsize[i].innerHTML);
    }
    var shopId = sessionStorage.getItem("shopId")
    var goodsIntroduce = document.getElementById("goodIntroduction").value
    // var userId = document.getElementById("inthis").innerHTML
    var bigId = document.getElementById("type").value
    var brandId = document.getElementById("brand").value
    img = document.getElementById('oImg').src
    var file = document.getElementById('ipt');
    var browse = document.getElementById("browse");
    console.log("------------------------------------------------------")
    // console.log(file.files[0])
    // console.log(browse.files)
    // console.log(browse.files.length)
                            //  console.log("------------------------------------------------------")
            // console.log(10086)
            // console.log(file.files[0]);
                                // var formData = new FormData()
    // console.log(formData)
    var userId = 76
                                // console.log("------------------------------------------------------")
    var goodsImg = document.getElementsByClassName("putImg")
    for(let i=0;i<goodsImg.length;i++){
        console.log("goodsImg")
        console.log(goodsImg[i].files[0])
        formData.append(`goodsImg`,goodsImg[i].files[0])
    }
    console.log("------------------------------------------------------")
    console.log(browse)
    console.log("------------------------------------------------------")
    for(let j = 0; j<browse.files.length; j++){
        console.log("files")
        console.log(browse.files[j])
        formData.append(`fileUpload`, browse.files[j])
    }
    formData.append('multipartFile',file.files[0]);
    // formData.append('multipartFile',browse.filelist)
            // console.log(formData)
            // var thefiles = document.getElementById('browse');
    // console.log(thefiles.files[0])
    // console.log(thefiles.files[1])
    // console.log(thefiles.files.length)
            // var theFiles = new Array();
            // for(let i = 0;i<thefiles.files.length ; i++){
            //     theFiles.push(thefiles.files[i])
        // theFiles.map(Number)     //以数字的形式返回新数组
        // console.log(goodssiz)
        // console.log(goodSize)
            // }
    // for(let i=0;i<theFiles.length;i++){
    //     formData.append(`files[${i}]`, theFiles)
    // }
                                    // formData.append('filelength',theFiles.length)
    // console.log(theFiles)
                                    // formData.append('files',theFiles);
    //------------------------------------------
    // formData.append('goodsPrice',goodsPrice);
    formData.append('goodsName',goodsName);
    // formData.append('stock',goodsStock);
    // formData.append('size',goodSize);
    // formData.append('color',goodColor);
    formData.append('introduction',goodsIntroduce);
    // formData.append('specName',specName);
    // formData.append('specContent',specContent);
    formData.append('shopId',shopId);
    formData.append('bigId',bigId);
    formData.append('brandId',brandId);
    formData.append('userId',userId);
    //------------------------------------------
    axios({
        url: `/home/add/bussiness/uploadGood`,
        data: formData,
        // params:{
        //     userId:userId,
        //     goodsPrice:goodsPrice,
        //     goodsName:goodsName,
        //     stock:goodsStock,
        //     size:goodSize,
        //     color:goodColor,
        //     introduction:goodsIntroduce,
        //     specName:specName,
        //     specContent:specContent,
        //     shopId:shopId,
        //     bigId:bigId,
        //     brandId:brandId,
        // },
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        method:'post'
    }).then(function(data){
        console.log(data)
        if(data.data.status ==200){
            document.getElementById("floatContent").innerHTML =`<div>上传成功，管理员正在审核中</div><button onclick='closethis()' class='newbtn'>确定</button>`;
            document.getElementById("floatContent").classList.remove("hide");
        }else{
            document.getElementById("floatContent").innerHTML =`<div>很抱歉</div><div>上传失败</div><button onclick='closethis()' class='newbtn'>确定</button>`;
            document.getElementById("floatContent").classList.remove("hide");
        }
    }).catch(function (error){
        console.log(error)
        document.getElementById("floatContent").innerHTML ="<div>"+ "很抱歉"+"</div>"+"<div>"+"请检查网络情况"+"</div>"+"<button onclick='closethis()' class='newbtn'>"+"确定"+"</button>";
        document.getElementById("floatContent").classList.remove("hide");
    })
}